package com.huawei.cloud.phone.management.adapter.pkg;

import com.huawei.cloud.phone.management.application.pkg.PkgService;
import com.huawei.cloud.phone.management.application.pkg.dto.PkgDTO;
import com.huawei.cloud.phone.management.common.exception.ParamParseException;
import com.huawei.cloud.phone.management.common.utils.JsonUtils;
import com.huawei.cloud.phone.management.common.validate.InstallGroup;
import com.huawei.cloud.phone.management.common.validate.UninstallGroup;
import com.huawei.cloud.phone.management.common.validate.ValidatorUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;

@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/pkg")
public class PkgController {

    private final PkgService pkgService;

    /**
     * 普通方式安装应用
     *
     * @param data  应用和手机信息
     * @param files 应用文件数据
     */
    @PostMapping("/install")
    public void installPkg(@RequestParam("data") String data, @RequestParam("files") MultipartFile[] files) {
        PkgDTO pkgDTO;
        try {
            pkgDTO = JsonUtils.parseData(data, PkgDTO.class);
        } catch (RuntimeException e) {
            throw new ParamParseException(e.getMessage());
        }
        pkgDTO.setFiles(Arrays.asList(files));
        ValidatorUtils.validate(pkgDTO, InstallGroup.class);
        pkgService.installPkg(pkgDTO);
    }

    /**
     * 卸载应用
     *
     * @param pkgDTO 应用和手机信息
     */
    @PostMapping("/uninstall")
    public void uninstallPkg(@RequestBody @Validated({UninstallGroup.class}) PkgDTO pkgDTO) {
        pkgService.uninstallPkg(pkgDTO);
    }

    /**
     * 共享应用方式安装应用
     *
     * @param data  应用和手机信息
     * @param files 应用文件数据
     */
    @PostMapping("/install-share")
    public void installSharePkg(@RequestParam("data") String data, @RequestParam("files") MultipartFile[] files) {
        PkgDTO pkgDTO;
        try {
            pkgDTO = JsonUtils.parseData(data, PkgDTO.class);
        } catch (RuntimeException e) {
            throw new ParamParseException(e.getMessage());
        }
        pkgDTO.setFiles(Arrays.asList(files));
        ValidatorUtils.validate(pkgDTO, InstallGroup.class);
        pkgService.installSharePkg(pkgDTO);
    }

    /**
     * 卸载应用
     *
     * @param pkgDTO 应用和手机信息
     */
    @PostMapping("/uninstall-share")
    public void uninstallSharePkg(@RequestBody @Validated({UninstallGroup.class}) PkgDTO pkgDTO) {
        pkgService.uninstallSharePkg(pkgDTO);
    }
}
